<template>
  <!--选规格-->
  <van-popup v-model="popupSpecs" round position="center" @close="closePopup">
    <div class="spec_box q5" :style="{ width: fun.getPhoneEnv() == 3 ? '375px' : '' }">
      <div class="flex-c good-spec-popup">
        <img :src="popThumb" alt="" />
        <div class="title clamp-2">{{ popTitle }}</div>
      </div>
      <div class="spec_a">
        <div v-for="(spec, i) in goodsInfo.has_many_specs" :key="i">
          <h5>{{ spec.title }}：</h5>
          <ul class="option">
            <li @click.stop="selectSpecs(item, item.id)" v-for="(item, i) in spec.has_many_specs_item" :key="i" :class="specidArray.includes(item.id) ? 'cur' : ''">
              {{ item.title }}
            </li>
          </ul>
        </div>
      </div>
      <div class="add_car">
        <ul class="car_btn flex-c">
          <li class="left" v-if="goodsInfo.point_goods">
            {{ popPrice }}<span>{{ integral }}</span>
          </li>
          <li class="left" v-else>
            <div class="good-price">
              <span>{{ $i18n.t("money") }}</span
              >{{ popPrice }}
            </div>
            <div class="vip-price" v-if="isMultiSpecs">
              <van-loading class="m-l-w6" size="16" color="#fdbc2e" v-show="specsVIPPrc == 0" />
              <span class="m-l-w6" v-show="specsVIPPrc">&nbsp;{{ vip_price_txt }}: {{ $i18n.t("money") }}{{ specsVIPPrc }} </span>
            </div>
          </li>
          <li class="right">
            <span v-show="!popNum && popStock >= 1 && !diyAddTxt" @click.stop="submitAction">{{ $i18n.t("category.加入购物车") }}</span>
            <span v-show="!popNum && popStock >= 1 && diyAddTxt" @click.stop="submitAction" style="width: auto;padding: 0 1rem;" v-html="diyAddTxt"></span>
            <span v-show="popStock <= 0" style="background: #999;">库存不足</span>
          </li>
          <div class="Box" v-show="popNum >= 1">
            <i class="iconfont icon-store_reduceLine" @click.stop="changeCount(popCard.id, popNum - 1, -1)"></i>
            <label class="show">{{ popNum }}</label>
            <i class="iconfont icon-store_plus" @click.stop="changeCount(popCard.id, popNum + 1, 1)"></i>
          </div>
        </ul>
      </div>
    </div>
  </van-popup>
</template>
<script>

import { mapState } from "vuex";

var specsManage = []; //选择池 用于排序
var optionsId = ""; //选择后的 规格ID
var optionsMaxCount = 1;
var OldGoodsNum = null;
export default {
  model: {
    prop: "popupSpecs",
    event: "onEmit"
  },
  props: {
    goodsInfo: {
      type: [],
      default: () => {
        [];
      }
    },
    popupSpecs: {
      type: Boolean,
      default: false
    },
    carts: {
      type: [],
      default: []
    },
    shopCart: {
      type: Boolean,
      default: true
    },
    // 新增自定义文字
    diyAddTxt:{
      type: String,
      default: ''
    }
  },
  components: { },
  data() {
    return {
      showGoodScreen: false,
      searchScreen: {},
      integral: window.localStorage.getItem("integral") || "积分",
      debounce_timer: null,
      brandShow: "",
      categoryShow: "",
      active: 9999,
      active2: true,
      allLoaded: false,
      topStatus: "",
      err: "",
      turl: "/category",
      arg: { index: 10, item: "pinch" },
      parentTitle: this.$i18n.t("推荐分类"),
      onelist: [],
      contentlist: {},
      contentlist_one: {},
      category_template: "01", //后台开启那个模板
      cartInfo: {},

      list: [],
      advimg: window.localStorage.adv_img,
      carts: [],
      cartIDs: [],
      specid: "", //规格ID
      specidArray: [],
      goodsCarts: [], //购物车转为goods key的数组
      goodsCartsTotal: [],
      activeName: [], //分类折叠面板
      secondaryId: "", //二级分类id
      threeId: "", //三级分类ID
      threeInfo: [], //三级商品列表
      show2: false, //规格弹窗
      showTitle: "", //分类折叠标题
      titleInfo: {}, //用于保存分类折叠时自定义标题分类
      foodInfo: [],
      popTitle: "",
      popPrice: "",
      popNum: 0,
      popStock: "",

      //more
      page: 1, //分页数，当前页数
      isLoadMore: false, //判断是否要加载更多的标志
      total_page: 0, //总页数
      activatId: "", //当前的分类id
      LoadMoreTest: "",
      scrollMargin: 0,

      isGetCart: true, //是否请求获取购物车接口数据
      ADImg: "", //广告图片地址
      ADUrl: "", //广告跳转链接
      isRecommend: true, //是否为推荐分类

      isCategoryMore: false, //装修01，03导航栏分类加载更多
      isCategory_total_page: 0,
      isCategoryPage: 1,

      main_category_page: 1,
      main_category_total: 0,

      isSelfPickCategory: false, //是否为供应商管理的自提点的分类页，#75504；如是，则只显示自提点关联的供应商的商品和平台商品（包含聚合供应链商品），其他供应商商品不显示，没有关联自提点的供应商商品也不显示。
      deliverId: 0, //自提点id

      isMultiSpecs: false, //多规格商品是否显示会员价
      specsVIPPrc: null //规格商品会员价
    };
  },
  watch: {
    popupSpecs: function(newV, oldV) {
      if (newV) {
        this.addGood(this.goodsInfo);
      }
    },
    carts: function(newV, oldV) {
      if (!this.shopCart && newV) {
        for (let i = 0; i < newV.length; i++) {
          if (newV[i].goods_id === this.goodsInfo.id && newV[i].option_id === optionsId) {
            this.popNum = newV[i].total;
            this.popCard = newV[i];
            break;
          }
          this.popNum = 0;
          this.popCard = {};
        }
      }
    }
  },
  computed: {
    ...mapState(["category", "blurst"]),
    zoneId() {
      if (this.$store.state.zoneId == "") {
        this.$store.commit("setZoneId", window.localStorage.getItem("zoneId"));
      }
      return this.$store.state.zoneId;
    },
    vip_price_txt() {
      if (this.$store.state.shopLanguage.goods) {
        // 会员价  系统自定义
        return this.$store.state.shopLanguage.goods.vip_price || "会员价";
      } else {
        return "会员价";
      }
    }
  },
  methods: {
    closePopup() {
      this.$emit("closePopup");
    },
    //弹窗提交确认
    submitAction() {
      let that = this;
      console.log("弹窗提交确认", optionsMaxCount);
      if (specsManage.length < this.goodsInfo.has_many_specs.length) {
        //请选择规格
        // this.show2 = false;
        this.$toast(this.goodsDescription);
        return;
      }
      if (optionsMaxCount == 0) {
        this.$toast("该规格库存不足！");
        return;
      }
      if (!this.shopCart) {
        // 不是商城的购物车,直接传递给父组件
        this.$emit("submitAction", { optionsId: optionsId, goodsInfo: this.goodsInfo });
        return;
      }
      $http.get("member.member-cart.store", { goods_id: this.goodsInfo.id, total: 1, option_id: optionsId }, "").then(
        response => {
          if (response.result === 1) {
            this.$store.commit("setCartNum", response.data.cart_num);
            this.$toast(response.msg);
            // that.updateData();
            that.popNum = that.popNum + 1;
            this.$emit("submitAction", { optionsId });
          } else {
            this.$toast(response.msg);
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    destroyData(_cid) {
      //清除该购物车商品id
      let that = this;
      $http.get("member.member-cart.destroy", { ids: _cid }).then(response => {
        if (response.result == 1) {
          that.popNum = 0;
          let _num = this.$store.state.cart_num - 1; //注意这里是购物车数量，不是购物车商品数量哦
          this.$store.commit("setCartNum", _num);
          // that.updateData();
          this.$emit("submitAction");
        } else {
          this.$toast(response.msg);
        }
      });
    },
    changeCount(_id, _num, index, _good) {
      let that = this;
      console.log(_id, _num, index, _good, "ppppppppppppppppppp");
      if (!this.shopCart) {
        // 不是商城的购物车,直接传递给父组件
        this.$emit("cartChange", {
          id: _id,
          num: _num
        });
        return;
      }
      if (_num <= 0) {
        this.destroyData(_id);
        return;
      }
      if (this.fun.isTextEmpty(_good) && _num - 1 >= optionsMaxCount) {
        //有规格的
        this.$toast("库存不足");
        return;
      } else if (!this.fun.isTextEmpty(_good) && _num >= _good.stock) {
        //无规格
        // console.log(that.goodsCartsTotal)
        // that.goodsCartsTotal[_good.id].total =5;
        this.$set(that.goodsCartsTotal[_good.id], "total", OldGoodsNum);
        this.$toast(`该商品最多购买数量为${_good.stock}`);
        return;
      }

      let json = {
        id: _id,
        num: _num
      };

      $http.get("member.member-cart.updateNumV2", json, "").then(
        response => {
          if (response.result === 1) {
            // that.updateData();
            this.$emit("submitAction", { optionsId: this.popCard.option_id });
            if (!that.fun.isTextEmpty(index)) {
              //规格商品
              switch (index) {
                case -1:
                  that.popNum = that.popNum - 1;
                  break;
                case 1:
                  that.popNum = that.popNum + 1;
                  break;
                default:
                  console.log("error");
              }
            }
          } else {
            this.$toast(response.msg);
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    addGood(good) {
      //价格权限
      if (good.vip_level_status && good.vip_level_status.status == 1) {
        this.$toast(good.vip_level_status.tips);
        return false;
      }
      this.popupSpecs = true;
      this.goodsInfo = good;

      this.initPopView(); //初始化弹窗view
    },
    //初始化弹窗view
    initPopView() {
      optionsId = "";
      specsManage = [];
      this.specid = "";
      this.popNum = 0;
      if (this.goodsInfo.has_option === 1) {
        //是否有规格
        // this.isShowMultiSpecsMemPrice(); //是否需要显示多规格会员价
        this.popTitle = this.goodsInfo.title; //设置默认图片
        this.popThumb = this.goodsInfo.thumb; //设置商品名
        this.popStock = this.goodsInfo.stock; //设置默认库存
        this.popCard = {};
        if (!this.specid.length) {
          if (this.goodsInfo.point_goods) {
            this.popPrice = this.goodsInfo.point_goods.min_point + "-" + this.goodsInfo.point_goods.max_point; //设置默认价格
          } else {
            this.popPrice = this.goodsInfo.min_price + "-" + this.goodsInfo.max_price; //设置默认价格
          }
        }

        this.goodsDescription = "请选择";
        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          this.goodsDescription += " " + this.goodsInfo.has_many_specs[i].title;
        }

        if (!optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
            if (this.goodsInfo.goods_option_ids && this.goodsInfo.goods_option_ids.length >= 0) {
              for (let j = 0; j < this.goodsInfo.has_many_specs[i].has_many_specs_item.length; j++) {
                if (this.goodsInfo.has_many_specs[i].has_many_specs_item[j].id == Number(this.goodsInfo.goods_option_ids[i])) {
                  this.selectSpecs(this.goodsInfo.has_many_specs[i].has_many_specs_item[j], this.goodsInfo.has_many_specs[i].has_many_specs_item[j].id);
                }
              }
            } else {
              this.selectSpecs(this.goodsInfo.has_many_specs[i].has_many_specs_item[0], this.goodsInfo.has_many_specs[i].has_many_specs_item[0].id);
            }
          }
        }
      } else {
        this.goodsDescription = "";
        optionsMaxCount = this.goodsInfo.stock; //设置最大购买量
      }
    },
    //界面选择规格触发事件
    selectSpecs(data, id) {
      //处理选择池
      this.manageSpecs(data);

      //处理规格组合选择状态
      this.setGoodsSpecs(data);

      //设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo(id);

      //判断当前购买总量与库存的关系
      this.getMaxCount();
    },
    //处理选择池
    manageSpecs(data) {
      var specsObject = new Object();
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;
      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      //排序
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setGoodsDescription();
    },
    //处理goodsDescription 数据
    setGoodsDescription() {
      var description = "";
      //相等代表全选了 体现语句
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.goodsDescription = description;
      } else {
        description = "请选择 ";

        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
              description += this.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.goodsDescription = description;
      }
    },
    //处理规格组合选择状态 过滤数据
    setGoodsSpecs(specs) {
      for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.goodsInfo.has_many_specs[i].id) {
          this.setGoodsSpecsStatus(this.goodsInfo.has_many_specs[i].has_many_specs_item, specs.id);
        }
      }
    },
    //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
    setGoodsSpecsStatus(specitem, id) {
      let options = []; //数据池

      for (let i = 0; i < this.goodsInfo.has_many_options.length; i++) {
        let _specs = this.goodsInfo.has_many_options[i].specs.split("_");
        //判断是否包含
        for (let j = 0; j < _specs.length; j++) {
          if (_specs[j] == id) {
            options.push(this.goodsInfo.has_many_options[i]);
          }
        }
      }

      for (let m = 0; m < options.length; m++) {
        let _specs = options[m].specs.split("_");
        for (let y = 0; y < _specs.length; y++) {
          if (_specs[y] != id && options[m].stock == 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = true;
              }
            }
          } else if (_specs[y] != id && options[m].stock > 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = false;
              }
            }
          }
        }
      }
    },
    //设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo(id) {
      //根据ID 排序 specsManage.sort();
      specsManage.sort(function(a, b) {
        return a.id - b.id;
      });
      if (specsManage.length === this.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
        this.specid = goodsSpecs;
        this.specidArray = goodsSpecs.split("_").map(Number);
        for (let i = 0; i < this.goodsInfo.has_many_options.length; i++) {
          if (goodsSpecs === this.setGoodsSpecsBySort(this.goodsInfo.has_many_options[i].specs)) {
            this.popmPrice = this.goodsInfo.has_many_options[i].market_price; //设置价格
            if (this.goodsInfo.point_goods) {
              this.popPrice = this.goodsInfo.point_goods.point_option[i].goods_point; //设置价格
            } else {
              this.popPrice = this.goodsInfo.has_many_options[i].product_price; //设置价格
            }
            this.popThumb = this.fun.isTextEmpty(this.goodsInfo.has_many_options[i].thumb) ? this.goodsInfo.thumb : this.goodsInfo.has_many_options[i].thumb; //设置图片
            this.popStock = this.goodsInfo.has_many_options[i].stock; //设置库存

            optionsId = this.goodsInfo.has_many_options[i].id; //设置规格ID，用于生成订单
            optionsMaxCount = this.goodsInfo.has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
            // console.log("库存最大数",optionsMaxCount)
            if (optionsMaxCount > 0) {
              this.popNum = 0;
            }
            if (this.isMultiSpecs) this.getMemberPrice(optionsId);
            break;
          } else {
            //最后一个还没匹配的
            if(this.goodsInfo.has_many_options.length == i + 1) {
              this.popStock = 0;
              optionsMaxCount = 0;
              console.log('未找到匹配的规格');
            }
          }
        }

        for (let i = 0; i < this.carts.length; i++) {
          if (this.carts[i].goods_id === this.goodsInfo.id && this.carts[i].option_id === optionsId) {
            this.popNum = this.carts[i].total;
            this.popCard = this.carts[i];
            break;
          }
          this.popNum = 0;
          this.popCard = {};
        }
      } else {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        this.specid = goodsSpecs;
      }
    },
    //处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); //先变成数组
      //_specs.sort();//排序
      _specs.sort(function(a, b) {
        return a - b;
      });

      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"

      return goodsSpecs;
    },
    getMemberPrice(_optionsId) {
      if (!_optionsId) return;
      this.specsVIPPrc = 0;
      $http
        .post("goods.other-info.option-vpi-price", { option_id: _optionsId }, null, true)
        .then(res => {
          if (res.result == 1) {
            this.specsVIPPrc = res.data.vip_price || null;
          } else {
            this.specsVIPPrc = null;
          }
        })
        .catch(error => {
          this.specsVIPPrc = null;
          console.log(error);
        });
    },
    //判断当前购买总量与库存的关系
    getMaxCount() {
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          //库存不足
          this.popNum = 0;
        }
        if (this.popNum > optionsMaxCount) {
          this.popNum = optionsMaxCount;
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.flex-c {
  display: flex;
  align-items: center;
  justify-content: center;
}

.clamp-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.spec_box {
  width: 16.875rem;
  background: #fff;
  border-radius: 0.5rem;
  padding: 0.75rem;

  .good-spec-popup {
    align-items: flex-start;

    img {
      width: 2.8125rem;
      height: 2.8125rem;
      background: #ededed;
      border-radius: 2px;
      margin-right: 6px;
    }

    .title {
      flex: 1;
      font-size: 13px;
      text-align: left;
      line-height: 1.125rem;
    }
  }

  .spec_a {
    margin-top: 0.625rem;
    height: 12rem;
    overflow-y: scroll;

    h5 {
      display: block;
      line-height: 2.5rem;
      font-size: 0.75rem;
      text-align: left;
    }

    .option {
      display: flex;
      flex-wrap: wrap;

      .cur {
        border: solid 0.0625rem #f15353;
        color: #f15353;
        background-color: rgba($color: #f15353, $alpha: 0.1);
      }

      li {
        font-size: 11px;
        padding: 0 0.875rem;
        line-height: 1.5625rem;
        margin-right: 0.625rem;
        margin-bottom: 0.625rem;
        background: #ededed;
        border: solid 0.0625rem #ededed;
        border-radius: 0.1875rem;
      }
    }
  }

  .add_car {
    padding-top: 0.75rem;
    width: 100%;
    border-top: solid 0.0625rem #ebebeb;

    .car_btn {
      justify-content: space-between;
      height: 100%;

      .left {
        color: #f15353;
        font-size: 16px;
        text-align: left;
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;

        .good-price,
        .vip-price {
          width: 100%;
        }

        .good-price {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .vip-price {
          font-size: 10px;
          color: #fdbc2e;
        }

        span {
          font-size: 10px;
        }
      }

      .right span {
        display: block;
        width: 5.5625rem;
        height: 1.875rem;
        line-height: 1.875rem;
        border-radius: 1rem;
        background: #f15353;
        color: #fff;
        font-size: 14px;
      }

      .Box {
        display: flex;

        i {
          width: 28px;
          height: 1.75rem;
          line-height: 1.75rem;
          font-size: 26px;
          color: #f15353;
        }

        .icon-store_reduceLine {
          color: #aaa;
        }

        label {
          right: 2.1875rem;
          color: #333;
          font-size: 12px;
          padding: 0;
          width: 1.5rem;
          height: 1.75rem;
          overflow: hidden;
          display: inline-block;
          text-align: center;
          line-height: 1.75rem;
          vertical-align: top;
          background-origin: content-box;
          background-color: transparent;
        }
      }
    }
  }
}
</style>
